<template>
  <div class="marketing-modern-root">
    <el-card class="modern-card search-card-modern">
      <el-row :gutter="16" class="search-row-modern">
        <el-col :span="6">
          <el-input v-model="searchForm.memberNumber" placeholder="会员编号" clearable class="modern-input" />
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchForm.memberName" placeholder="会员姓名" clearable class="modern-input" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.memberLevel" placeholder="会员等级" clearable class="modern-input">
            <el-option label="普通会员" value="普通会员" />
            <el-option label="银卡会员" value="银卡会员" />
            <el-option label="金卡会员" value="金卡会员" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="searchForm.dateRange"
                          type="daterange"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                          clearable class="modern-input"
                          style="width: 250px"
          />
        </el-col>
      </el-row>
      <div class="search-buttons-modern">
        <el-button type="primary" class="modern-btn-main" @click="handleSearch">查询</el-button>
        <el-button class="modern-btn-sub" @click="() => {}">导出</el-button>

      </div>
    </el-card>
    <el-row :gutter="24" class="stats-row-modern">
      <el-col :span="6">
        <el-card class="stats-card-modern stats-blue-bgcard">
          <div class="stats-content-modern">
            <div class="stats-title-modern">总会员数</div>
            <div class="stats-amount-modern stats-blue-num">{{ totalMembers }}</div>
            <div class="stats-trend-badge stats-blue-bg">本月新增 {{ newMembersCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-yellow-bgcard">
          <div class="stats-content-modern">
            <div class="stats-title-modern">金卡会员</div>
            <div class="stats-amount-modern stats-yellow-num">{{ goldMembersCount }}</div>
            <div class="stats-trend-badge stats-yellow-bg">占比 {{ goldMembersPercentage }}%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-gray-bgcard">
          <div class="stats-content-modern">
            <div class="stats-title-modern">银卡会员</div>
            <div class="stats-amount-modern stats-gray-num">{{ silverMembersCount }}</div>
            <div class="stats-trend-badge stats-gray-bg">占比 {{ silverMembersPercentage }}%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-green-bgcard">
          <div class="stats-content-modern">
            <div class="stats-title-modern">活跃会员</div>
            <div class="stats-amount-modern stats-green-num">{{ activeMembersCount }}</div>
            <div class="stats-trend-badge stats-green-bg">近30天消费</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="modern-card table-card-modern">
      <div class="table-actions-modern">
        <div class="flex justify-between items-center" style="display: flex;text-align: center;margin-bottom: 5px">
          <h2 class="modern-table-title" >会员管理</h2>
        </div>
      </div>
      <el-table :data="pagedMembers" stripe class="modern-table">
        <el-table-column prop="name" label="姓名" width="120" />
        <!-- 会员等级列补充特权提示 -->
        <el-table-column label="等级" width="180">
          <template #default="{ row }">
            <div class="level-with-tooltip">
              <el-tag :type="getMemberLevelType(row.memberLevel)" size="small">{{ row.memberLevel }}</el-tag>
              <el-tooltip effect="dark" :content="getLevelPrivileges(row.memberLevel)" placement="top">
                <el-icon class="info-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pointsBalance" label="积分余额" width="120" />
        <el-table-column prop="lastConsumptionDate" label="最近消费日期" width="150">
          <template #default="{ row }">
            {{ row.lastConsumptionDate ? dayjs(row.lastConsumptionDate).format('YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.memberStatus === '正常' ? 'success' : 'danger'" size="small">{{ row.memberStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="primary" size="small" class="modern-btn-main" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" class="modern-btn-danger" @click="handleDelete(row)">删除</el-button>
            <el-button type="primary" size="small" @click="openConsumptionRecord(row)">消费记录</el-button>
            <!-- 新增：积分兑换按钮 -->
            <el-button type="info" size="small" class="modern-btn-exchange" @click="openExchangeDialog(row)">积分兑换</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container-modern">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handlePageSizeChange"
            layout="total, prev, pager, next, sizes, jumper"
        />
      </div>
    </el-card>


    <!-- 消费记录对话框 -->
    <el-dialog title="消费记录" v-model="consumptionDialogVisible" width="700px">
      <el-table :data="filteredConsumptionRecords" stripe class="modern-table">
        <el-table-column prop="date" label="日期" width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === '消费' ? 'primary' : 'success'" size="small">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" width="250" />
        <el-table-column prop="amount" label="消费金额(元)" width="120">
          <template #default="{ row }">{{ row.amount || 0 }}</template>
        </el-table-column>
        <el-table-column prop="points" label="积分变动" width="120">
          <template #default="{ row }">
        <span :style="{ color: row.points >= 0 ? 'green' : 'red' }">
          {{ row.points >= 0 ? '+' : '' }}{{ row.points }}
        </span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="consumptionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 积分兑换对话框 -->
    <el-dialog title="积分兑换" v-model="exchangeDialogVisible" width="500px">
      <el-form ref="exchangeFormRef" :model="exchangeForm" :rules="exchangeRules" label-width="120px">
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="exchangeForm.name" disabled />
        </el-form-item>
        <el-form-item label="当前积分" prop="currentPoints">
          <el-input v-model="exchangeForm.currentPoints" disabled />
        </el-form-item>
        <el-form-item label="兑换商品" prop="productId">
          <el-select v-model="exchangeForm.productId" placeholder="选择兑换商品">
            <el-option
                v-for="product in exchangeProducts"
                :key="product.id"
                :label="product.name"
                :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所需积分" prop="requiredPoints">
          <el-input v-model="exchangeForm.requiredPoints" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exchangeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleExchangeConfirm">确认兑换</el-button>
      </template>
    </el-dialog>

    <!-- 编辑会员对话框 -->
    <el-dialog title="编辑会员" v-model="editDialogVisible" width="500px">
      <el-form ref="memberFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="会员编号" prop="memberNumber">
          <el-input v-model="editForm.memberNumber" placeholder="会员编号" disabled />
        </el-form-item>
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入11位手机号码" />
        </el-form-item>
        <el-form-item label="会员等级" prop="memberLevel">
          <el-select v-model="editForm.memberLevel" placeholder="选择会员等级">
            <el-option label="普通会员" value="普通会员" />
            <el-option label="银卡会员" value="银卡会员" />
            <el-option label="金卡会员" value="金卡会员" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物数量" prop="petCount">
          <el-input-number
              v-model.number="editForm.petCount"
              :min="0"
              placeholder="宠物数量"
          />
        </el-form-item>
        <el-form-item label="积分余额" prop="pointsBalance">
          <el-input v-model.number="editForm.pointsBalance" placeholder="积分余额" disabled/>
        </el-form-item>
        <el-form-item label="最近消费日期" prop="lastConsumptionDate">
          <el-date-picker
              v-model="editForm.lastConsumptionDate"
              type="date"
              placeholder="选择最近消费日期"
          />
        </el-form-item>
        <el-form-item label="会员状态" prop="memberStatus">
          <el-select v-model="editForm.memberStatus" placeholder="选择会员状态">
            <el-option label="正常" value="正常" />
            <el-option label="冻结" value="冻结" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">
            确认编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useCustomerStore } from '../stores/customerStore'
import { useConsumptionStore } from '../stores/consumptionStore'
import { useOrderStore } from '../stores/orderStore'

const customerStore = useCustomerStore()
const consumptionStore = useConsumptionStore()
const orderStore = useOrderStore()

// 消费记录列表（包含消费和兑换记录）
const consumptionRecords = computed(() => consumptionStore.records)
// 消费记录对话框
const consumptionDialogVisible = ref(false);
const currentMemberNumber = ref(""); // 当前查看记录的会员编号

// 过滤当前会员的消费记录
const filteredConsumptionRecords = computed(() => {
  return consumptionRecords.value.filter(
      record => record.memberName === currentMemberNumber.value
  );
});

// 打开消费记录对话框
const openConsumptionRecord = (row) => {
  currentMemberNumber.value = row.name; // 用会员姓名做唯一标识
  // 过滤出当前会员的记录
  filteredConsumptionRecords.value = consumptionRecords.value.filter(
      record => record.memberName === row.name
  );
  consumptionDialogVisible.value = true;
};

// 兑换商品列表（模拟数据，实际从后端获取）
const exchangeProducts = ref([
  { id: 1, name: "宠物零食大礼包", points: 500 },
  { id: 2, name: "免费洗澡服务", points: 1000 },
  { id: 3, name: "宠物玩具套装", points: 800 }
]);

// 兑换表单
const exchangeDialogVisible = ref(false);
const exchangeForm = ref({
  memberNumber: "",
  memberName: "",
  currentPoints: 0,
  productId: "",
  requiredPoints: 0
});
const exchangeRules = {
  productId: [{ required: true, message: "请选择兑换商品", trigger: "change" }],
  requiredPoints: [{ required: true, message: "请选择兑换商品", trigger: "change" }]
};
const exchangeFormRef = ref(null);

// 打开兑换对话框
const openExchangeDialog = (row) => {
  exchangeForm.value = {
    memberNumber: row.memberNumber,
    name: row.name,
    currentPoints: row.pointsBalance,
    productId: "",
    requiredPoints: 0
  };
  exchangeDialogVisible.value = true;
};

// 监听商品选择，自动填充所需积分
watch(
    () => exchangeForm.value.productId,
    (val) => {
      const product = exchangeProducts.value.find(p => p.id === val);
      exchangeForm.value.requiredPoints = product ? product.points : 0;
    }
);

// 确认兑换
const handleExchangeConfirm = () => {
  exchangeFormRef.value.validate((valid) => {
    if (valid) {
      // 修正：直接用表单的当前积分校验
      console.log('校验积分:', exchangeForm.value.currentPoints, exchangeForm.value.requiredPoints);
      if (exchangeForm.value.currentPoints < exchangeForm.value.requiredPoints) {
        ElMessage.error("积分不足，无法兑换");
        return;
      }
      // 获取兑换商品名称
      const product = exchangeProducts.value.find(p => p.id === exchangeForm.value.productId);
      // 更新会员积分（同步store）
      const memberIndex = customerStore.customers.findIndex(
        m => m.name === exchangeForm.value.name
      );
      if (memberIndex !== -1) {
        customerStore.customers[memberIndex].pointsBalance -= exchangeForm.value.requiredPoints;
        customerStore.customers[memberIndex].lastConsumptionDate = dayjs().format("YYYY-MM-DD");
      }
      // 添加兑换记录到消费记录列表
      consumptionStore.addRecord({
        id: `EXC${dayjs().format("YYYYMMDDHHmmss")}`,
        memberName: exchangeForm.value.name, // 用会员姓名做唯一标识
        type: "兑换",
        amount: 0,
        points: -exchangeForm.value.requiredPoints,
        description: `兑换商品：${product.name}`,
        date: dayjs().format("YYYY-MM-DD")
      });
      ElMessage.success("兑换成功");
      exchangeDialogVisible.value = false;
    }
  });
};

// 会员等级特权说明
const getLevelPrivileges = (level) => {
  const privileges = {
    "普通会员": "1. 消费1元累计1积分\n2. 生日当月消费享9.5折",
    "银卡会员": "1. 消费1元累计1.2积分\n2. 生日当月消费享9折\n3. 免费洗澡服务每月1次",
    "金卡会员": "1. 消费1元累计1.5积分\n2. 生日当月消费享8.5折\n3. 免费洗澡服务每月2次\n4. 优先预约特权"
  };
  return privileges[level] || "暂无特权";
};

// 搜索表单
const searchForm = reactive({
  memberNumber: '',
  memberName: '',
  memberLevel: '',
  dateRange: []
})

// 新增会员相关
const addDialogVisible = ref(false)
const addForm = reactive({
  memberName: '',
  phone: '',
  memberLevel: '普通会员',
  petCount: 0,
  pointsBalance: 0, // 新增积分余额字段
  lastConsumptionDate: '' // 新增最近消费日期字段
})
const addRules = {
  memberName: [
    { required: true, message: '请输入会员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
  ],
  memberLevel: [
    { required: true, message: '请选择会员等级', trigger: 'change' }
  ],
  petCount: [
    { required: true, message: '请输入宠物数量', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效数字'))
        } else if (value < 0) {
          callback(new Error('宠物数量不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  pointsBalance: [
    { required: true, message: '请输入积分余额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效数字'))
        } else if (value < 0) {
          callback(new Error('积分余额不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  lastConsumptionDate: [
    { required: true, message: '请选择最近消费日期', trigger: 'change' }
  ]
}
const addFormRef = ref(null)

// 编辑会员相关
const editDialogVisible = ref(false)
const editForm = ref({
  memberNumber: '',
  memberName: '',
  phone: '',
  memberLevel: '普通会员',
  petCount: 0,
  pointsBalance: 0,
  lastConsumptionDate: '',
  memberStatus: '正常'
})
const editRules = {
  memberName: [
    { required: true, message: '请输入会员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
  ],
  memberLevel: [
    { required: true, message: '请选择会员等级', trigger: 'change' }
  ],
  petCount: [
    { required: true, message: '请输入宠物数量', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (typeof value !== 'number' || isNaN(value)) {
          callback(new Error('请输入有效数字'))
        } else if (value < 0) {
          callback(new Error('宠物数量不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  pointsBalance: [
    { required: true, message: '请输入积分余额', trigger: 'blur' },
    { type: 'number', message: '请输入有效数字', trigger: 'blur' }
  ],
  lastConsumptionDate: [
    { required: true, message: '请选择最近消费日期', trigger: 'change' }
  ],
  memberStatus: [
    { required: true, message: '请选择会员状态', trigger: 'change' }
  ]
}
const memberFormRef = ref(null)
let currentEditMember = null

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = computed(() => filteredMembers.value.length)
const pagedMembers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredMembers.value.slice(start, start + pageSize.value)
})
const handlePageChange = (page) => {
  currentPage.value = page
}
const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 打开新增对话框
const openAddDialog = () => {
  addForm.memberName = ''
  addForm.phone = ''
  addForm.memberLevel = '普通会员'
  addForm.petCount = 0
  addFormRef.value?.resetFields()
  addDialogVisible.value = true
}

// 确认新增会员
const handleAddConfirm = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      const today = dayjs().format('YYYYMMDD')
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
      const newMemberNumber = `MEM${today}${randomNum}`
      // 格式化日期
      const formattedDate = addForm.lastConsumptionDate
          ? dayjs(addForm.lastConsumptionDate).format('YYYY-MM-DD')
          : ''
      customerStore.addCustomer({
        id: newMemberNumber,
        memberNumber: newMemberNumber,
        name: addForm.name,
        phone: addForm.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
        memberLevel: addForm.memberLevel,
        pointsBalance: addForm.pointsBalance,
        registrationDate: dayjs().format('YYYY-MM-DD'),
        petCount: addForm.petCount,
        lastConsumptionDate: formattedDate,
        memberStatus: '正常',
        isMember: true,
        pets: []
      })
      ElMessage.success('会员添加成功')
      addDialogVisible.value = false
      currentPage.value = 1 // 新增后跳到第一页
    } else {
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

// 打开编辑对话框（点击"编辑"按钮时调用，传入当前行数据）
const openEditDialog = (row) => {
  currentEditMember = row;
  // 直接替换整个表单对象（关键：避免引用残留）
  editForm.value = {
    memberNumber: row.memberNumber,
    name: row.name,
    // 手机号还原（处理脱敏）
    phone: row.phone.replace('****', row.phone.slice(3, 7)),
    memberLevel: row.memberLevel,
    petCount: row.pets?.length ?? 0,
    pointsBalance: row.pointsBalance,
    lastConsumptionDate: dayjs(row.lastConsumptionDate).format('YYYY-MM-DD'),
    memberStatus: row.memberStatus
  };

  // 重置验证状态
  if (memberFormRef.value) {
    memberFormRef.value.clearValidate();
    memberFormRef.value.resetFields();
    // 手动重置字段状态
    memberFormRef.value.fields.forEach(field => {
      field.touched = false;
      field.dirty = false;
      field.errorMessage = '';
    });
  }

  editDialogVisible.value = true;
};

// 确认编辑会员
const handleEditConfirm = () => {
  memberFormRef.value.validate((valid) => {
    if (valid) {
      const { memberName, phone, memberLevel, petCount, pointsBalance, lastConsumptionDate, memberStatus } = editForm.value;
      // 手机号重新脱敏
      const formattedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      // 格式化日期
      const formattedDate = dayjs(lastConsumptionDate).format('YYYY-MM-DD');

      const index = customerStore.customers.findIndex(member => member.id === currentEditMember.id);
      if (index !== -1) {
        customerStore.updateCustomer(currentEditMember.id, {
          memberName,
          phone: formattedPhone,
          memberLevel,
          petCount,
          pointsBalance,
          lastConsumptionDate: formattedDate,
          memberStatus
        });
        ElMessage.success('会员信息更新成功');
        editDialogVisible.value = false;
      }
    }
  });
};

// 只取 isMember: true 的客户，映射 lastConsumptionDate 字段
const members = computed(() => {
  return customerStore.customers
    .filter(c => c.isMember)
    .map(c => {
      const orders = orderStore.orders.filter(o => o.customerName === c.name)
      const lastOrder = orders.length > 0 ? orders.reduce((a, b) => (a.transactionDate > b.transactionDate ? a : b)) : null
      return {
        ...c,
        lastConsumptionDate: lastOrder ? lastOrder.transactionDate : ''
      }
    })
})

// 统计、分页、搜索等全部基于 members
const filteredMembers = computed(() => {
  let result = [...members.value]
  if (searchForm.memberNumber) {
    result = result.filter(member => member.memberNumber.includes(searchForm.memberNumber))
  }
  if (searchForm.name) {
    result = result.filter(member => member.name.includes(searchForm.name))
  }
  if (searchForm.memberLevel) {
    result = result.filter(member => member.memberLevel === searchForm.memberLevel)
  }
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    const start = dayjs(startDate).format('YYYY-MM-DD')
    const end = dayjs(endDate).format('YYYY-MM-DD')
    result = result.filter(member => {
      if (!member.lastConsumptionDate) return false
      const last = dayjs(member.lastConsumptionDate).format('YYYY-MM-DD')
      return last >= start && last <= end
    })
  }
  return result
})

// 统计数据
const totalMembers = computed(() => members.value.length)
const newMembersCount = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return members.value.filter(member => member.registrationDate === today).length
})
const goldMembersCount = computed(() =>
  members.value.filter(member => member.memberLevel === '金卡会员').length
)
const silverMembersCount = computed(() =>
  members.value.filter(member => member.memberLevel === '银卡会员').length
)
const goldMembersPercentage = computed(() => {
  if (totalMembers.value === 0) return 0
  return ((goldMembersCount.value / totalMembers.value) * 100).toFixed(1)
})
const silverMembersPercentage = computed(() => {
  if (totalMembers.value === 0) return 0
  return ((silverMembersCount.value / totalMembers.value) * 100).toFixed(1)
})
const activeMembersCount = computed(() => {
  const thirtyDaysAgo = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
  return members.value.filter(member =>
    member.lastConsumptionDate && member.lastConsumptionDate >= thirtyDaysAgo
  ).length
})

// 获取会员等级标签类型
const getMemberLevelType = (level) => {
  switch (level) {
    case '金卡会员': return 'warning'
    case '银卡会员': return 'info'
    default: return 'primary'
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 查询后跳到第一页
  if (
      !searchForm.memberNumber &&
      !searchForm.name &&
      !searchForm.memberLevel &&
      !searchForm.dateRange?.length
  ) {
    ElMessage.warning('请输入至少一个搜索条件')
    return
  }
  ElMessage.success('搜索成功')
}

// 处理删除会员
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除该会员吗？此操作不可恢复',
      '提示',
      { type: 'warning' }
  ).then(() => {
    customerStore.deleteCustomer(row.id)
    // 如果当前页无数据且不是第一页，自动跳到上一页
    if (pagedMembers.value.length === 0 && currentPage.value > 1) {
      currentPage.value--
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 模拟加载数据
onMounted(() => {
  // setTimeout(() => {
  //   memberStore.members = [
  //     ...memberStore.members,
  //     {
  //       id: 'MEM202501122',
  //       memberNumber: 'MEM202501122',
  //       memberName: '赵刚',
  //       phone: '135****7890',
  //       memberLevel: '金卡会员',
  //       pointsBalance: 2560,
  //       registrationDate: '2025-02-18',
  //       petCount: 2,
  //       lastConsumptionDate: '2025-06-05',
  //       memberStatus: '正常',
  //     }
  //   ]
  // }, 500)
})

const phoneRules = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
];
const emailRules = [
  { required: true, message: '请输入邮箱', trigger: 'blur' },
  { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
];
</script>

<style scoped>
/* 积分兑换按钮样式 */
.modern-btn-exchange {
  border-radius: 10px;
  font-weight: 600;
  background: #06b6d4; /* 青色系，区分其他按钮 */
  border: none;
  margin-left: 10px;
  color: #fff;
}
.modern-btn-exchange:hover {
  background: #0891b2;
  color: #fff;
}
/* 充值成功弹窗样式补充 */
.success-content {
  text-align: center;
  padding: 30px 0;
}
.success-icon {
  font-size: 70px;
  margin-bottom: 20px;
}
.success-details {
  font-size: 16px;
  color: #333;
  line-height: 2;
}

/* 充值按钮样式 */
.modern-btn-recharge {
  border-radius: 10px;
  font-weight: 600;
  background: #10b981;
  border: none;
  margin-left: 10px;
}
.modern-btn-recharge:hover {
  background: #059669;
  color: #fff;
}

/* 支付方式单选框样式 */
.el-radio-group {
  display: flex;
  gap: 15px;
  margin-top: 5px;
}
.el-radio {
  flex: 1;
  text-align: center;
}

/* 积分转换提示样式 */
.el-form-item__content .el-input__inner[disabled] {
  color: #10b981;
  background-color: #f0fdf4;
}
.marketing-modern-root {
  padding: 40px 32px;
  background: #f7f9fb;
  min-height: 100vh;
}
.modern-card {
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  border: none;
  margin-bottom: 28px;
}
.search-card-modern {
  margin-bottom: 28px;
  padding: 18px 18px 8px 18px;
}
.search-row-modern {
  margin-bottom: 0;
}
.search-buttons-modern {
  margin-top: 14px;
  display: flex;
  gap: 14px;
}
.stats-row-modern {
  margin-bottom: 28px;
}
.stats-card-modern {
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  border: none;
  padding: 0;
}
.stats-content-modern {
  padding: 30px 0 18px 0;
  text-align: center;
}
.stats-title-modern {
  font-size: 14px;
  font-weight: 400;
  color: #7b8191;
  margin-bottom: 0;
  margin-top: 8px;
}
.stats-amount-modern {
  font-size: 36px;
  font-weight: bold;
  color: #22223b;
  margin-bottom: 0;
}
.stats-trend-badge {
  display: inline-block;
  border-radius: 12px;
  padding: 2px 12px;
  font-size: 13px;
  font-weight: 500;
  margin-top: 10px;
  background: #f3f4f6;
}
.stats-blue-bgcard { background: #e0e7ff; }
.stats-yellow-bgcard { background: #fef9c3; }
.stats-gray-bgcard { background: #f3f4f6; }
.stats-green-bgcard { background: #e0fbe6; }
.stats-blue-num { color: #2563eb; }
.stats-yellow-num { color: #eab308; }
.stats-gray-num { color: #64748b; }
.stats-green-num { color: #22c55e; }
.table-card-modern {
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  border: none;
  padding: 0 0 10px 0;
}
.table-actions-modern {
  display: flex;
  align-items: center;
  padding: 18px 0 0 0;
  border-bottom: 1px solid #f0f1f3;
  margin-bottom: 0;
}
.modern-table-title {
  font-size: 20px;
  font-weight: 600;
  color: #22223b;
  margin: 0;
}
.modern-table {
  border-radius: 12px;
  overflow: hidden;
  font-size: 15px;
}
.modern-table .el-table__header th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
  border-bottom: 1.5px solid #e5e7eb;
}
.modern-table .el-table__row:hover td {
  background: #f1f5f9;
}
.modern-table .el-table__cell {
  border-bottom: 1px solid #f3f4f6;
}
.modern-table .el-button {
  border-radius: 8px !important;
}
.modern-btn-main {
  border-radius: 10px;
  font-weight: 600;
  background: #2563eb;
  border: none;
  color: #fff;
  transition: background 0.2s;
}
.modern-btn-main:hover {
  background: #1d4ed8;
}
.modern-btn-sub {
  border-radius: 10px;
  font-weight: 500;
  background: #f3f4f6;
  color: #374151;
  border: none;
}
.modern-btn-sub:hover {
  background: #e5e7eb;
}
.modern-btn-danger {
  border-radius: 10px;
  font-weight: 500;
  background: #f87171;
  color: #fff;
  border: none;
}
.modern-btn-danger:hover {
  background: #ef4444;
}
.pagination-container-modern {
  margin-top: 18px;
  text-align: right;
}
.modern-input {
  border-radius: 8px;
  font-size: 15px;
}
</style>
